﻿using System;

namespace FactoryPattern.ReflectFactory;

/// <summary>
///     反射工厂模式
///     是针对简单工厂模式的一种改进
/// </summary>
public static class ReflectFactory
{
    public abstract class AbstractCar
    {
        protected abstract void DoOperation();

        public void GetInfo()
        {
            Console.WriteLine($"I am {GetType().Name}.");
        }
    }

    public class ConcreteCarA : AbstractCar
    {
        protected override void DoOperation()
        {
            Console.WriteLine("ConcreteCarA do operation");
        }
    }

    public class ConcreteCarB : AbstractCar
    {
        protected override void DoOperation()
        {
            Console.WriteLine("ConcreteCarB do operation");
        }
    }

    public static void TestReflectFactory()
    {
        Console.WriteLine("反射工厂模式：");
        var productA = Create("FactoryPattern.ReflectFactory.ReflectFactory+ConcreteCarA");
        var productB = Create("FactoryPattern.ReflectFactory.ReflectFactory+ConcreteCarB");
        productA.GetInfo();
        productB.GetInfo();
    }

    public static AbstractCar Create(string typeName)
    {
        Type type = Type.GetType(typeName, true, true);
        var instance = type.Assembly.CreateInstance(typeName) as AbstractCar;
        return instance;
    }
}